package com.example.teaculture.activity;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.example.teaculture.DB.DBOpenHelper;
import com.example.teaculture.DB.FavorDao;
import com.example.teaculture.DB.HistoryDao;
import com.example.teaculture.R;
import com.example.teaculture.model.Favor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FavorActivity extends AppCompatActivity {
    private Toolbar toolbar;
    private DBOpenHelper helper;
    private SQLiteDatabase sd;
    private ArrayList<Favor> favorlist;
    private List<Map<String, String>> data = new ArrayList<>();
    private ListView lv;
    private ImageView iv_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_favor);
        toolbar = findViewById(R.id.toolbar);
        lv = findViewById(R.id.lv_favor);
        iv_back = findViewById(R.id.iv_back);
        toolbar.setTitle("我的收藏");
        //创建或打开数据库
        helper = new DBOpenHelper(FavorActivity.this);
        sd = helper.getReadableDatabase();
        favorlist = new ArrayList<>();

        FavorDao favorDao = new FavorDao(FavorActivity.this);
        List<Favor> list = favorDao.findSelected();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                Log.i("TAG:", "    " + list.get(i).getTitle());
                Map<String, String> map = new HashMap<>();
                map.put("标题", list.get(i).getTitle());
                data.add(map);
            }
        }
        lv.setAdapter(new SimpleAdapter(this, data, android.R.layout.simple_list_item_1,
                new String[]{"标题"},            //每行显示一个姓名
                new int[]{android.R.id.text1}   //名字在text1上显示
        ));

        HistoryDao historyDao = new HistoryDao(FavorActivity.this);
        lv.setOnItemClickListener((adapterView, view, i, l) -> {
            Favor favor = favorDao.selectByDocId(list.get(i).getDocid());
            historyDao.insertDetsilNews(favor);
            Intent intent = new Intent(this, FavorDetailActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.putExtra("url", favor.getUrl());
            intent.putExtra("title", favor.getTitle());
            startActivity(intent);
        });

    }

    public void fback(View view) {
        this.finish();
    }
}
